//
//  AccountLogin.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/12/6.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "AccountLogin.h"
#import "UserModel.h"
#import "NSString+MD5.h"

#import <SVProgressHUD.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>


@import FirebaseCore;
@import FirebaseInstanceID;
@import FirebaseMessaging;

@interface AccountLogin()

@property (strong , nonatomic) MBProgressHUD * waitHud;

@property (strong , nonatomic) UserModel * userModel;

@end

@implementation AccountLogin

-(UserModel *)userModel{
    
    if (!_userModel) {
        
        _userModel = [[UserModel alloc]init];
        
    }
    
    return _userModel;
    
}

-(MBProgressHUD *)waitHud{
    if (!_waitHud) {
        
    }
    return _waitHud;
}

- (instancetype)initWithAccountLogin
{
    self = [super init];
    if (self) {
//        [self accessToken];
    }
    return self;
}

+(instancetype)accountLogin{
    
    return [[self alloc]initWithAccountLogin];
    
}

-(void)accessToken:(void (^)())success{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * password = [userDefaults objectForKey:UD_PASSWORD];
    
    NSString * username = [userDefaults objectForKey:UD_USERNAME];
    
    if (!password && !username && ![userDefaults boolForKey:USER_IS_LOGIN]) {
        
        return;
        
    }
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    parameters[NC_USER_GUID] = [self getUniqueStrByUUID];
    parameters[NC_TERMINAL_MODEL] = @"ffffffff";
    parameters[NC_PLAT_FORM] = @"IOS";
    parameters[NC_ACCOUNT_TYPE] = @1;
    parameters[NC_USER_NAME] = username;
    
    NSString * newPassword = [NSString stringWithFormat:@"HYZ%@%@",username,password];
    
    NSString * md5Password = [NSString stringToMD5:newPassword];
    
    parameters[NC_USER_PASSWORD] = md5Password;
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",NC_SERVICE_URL,NC_DEBUG_LOGIN];
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //收起waithud
        [self.waitHud hideAnimated:YES];
        
        //判断nav做何动画
//        self.isLogin = YES;
        
        //判断是否登录成功
        int idNumber = [[responseObject valueForKey:NC_USER_ID] intValue];
        
        NSString *tokenPass = [responseObject valueForKey:NC_TOKEN_PASS];
        
        int clientType = [[responseObject valueForKey:NC_CLIENT_TYPE] intValue];
        
        if (!(idNumber > 0) || !(tokenPass.length > 0) || !(clientType > 0)) {
            
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            [SVProgressHUD dismissWithDelay:1];
            
            return;
            
        }
        
        
        UserModel * userModel = [[UserModel alloc]init];
        
        userModel.userID = [responseObject valueForKey:@"Id"];
        
        userModel.clientType = [responseObject valueForKey:@"ClientType"];
        
        userModel.tokenPass = [responseObject valueForKey:@"TokenPass"];
        
        userModel.userName = [responseObject valueForKey:@"UserName"];
        
        //推送绑定账号
        
        [[FIRMessaging messaging] subscribeToTopic:[NSString stringWithFormat:@"%@%@%@",NC_TOPICS,NC_PUSH,self.userModel.userID]];
        
        
        NSLog(@"success %@",responseObject);
        
        success();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //收起waithud
        [self.waitHud hideAnimated:YES];
        
        [SVProgressHUD showErrorWithStatus:@"Incorrect username or password.Please try again."];
        
        [SVProgressHUD dismissWithDelay:1];
        
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark 获取GUID
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}

#pragma mark gettime
-(void)getTimeInfo{
    
    NSDictionary * dict = self.userModel.deviceByAccountArray[7];
    
    NSString * seriaNumber = [dict valueForKey:@"SerialNumber"];
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    parameters[@"StartTime"] = @201612300000;
    parameters[@"EndTime"] = @201612302359;
    parameters[@"SerialNumber"] = seriaNumber;
    parameters[@"Id"] = self.userModel.userID;
    parameters[@"ClientType"] = self.userModel.clientType;
    parameters[@"TokenPass"] = self.userModel.tokenPass;
    
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVICE_URL,@"WebApi/GPSData/GetLastStatusData"];
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        
        NSLog(@"success %@",responseObject);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark 批量获取最后状态信息
-(void)getLastStatusData{
 
    NSDictionary * dict = self.userModel.deviceByAccountArray[6];
    
    NSString * seriaNumber = [dict valueForKey:@"SerialNumber"];
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    
    parameters[@"ListSerialNumber"] = seriaNumber;
    parameters[@"Id"] = self.userModel.userID;
    parameters[@"ClientType"] = self.userModel.clientType;
    parameters[@"TokenPass"] = self.userModel.tokenPass;
    
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVICE_URL,GET_LAST_STATUS_DATA];
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        
        NSLog(@"success %@",responseObject);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);
        
    }];

    
}

-(void)getNotifications{
    
    NSDictionary * dict = self.userModel.deviceByAccountArray[7];
    
    NSString * seriaNumber = [dict valueForKey:@"SerialNumber"];
    
    NSMutableDictionary * parameters = [ NSMutableDictionary dictionary];
    
    parameters[@"ListSerialNumber"] = seriaNumber;
    parameters[@"Id"] = self.userModel.userID;
    parameters[@"ClientType"] = self.userModel.clientType;
    parameters[@"TokenPass"] = self.userModel.tokenPass;
    
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    NSString * postUrl = [NSString stringWithFormat:@"%@%@",SERVICE_URL,@"WebApi/GPSData/GetLastEventDataBySns"];
    
    [manager POST:postUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        
        NSLog(@"success %@",responseObject);
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"%@",error);
        
    }];
    
    
    
}

@end
